import { reqUserLog } from '@/apis/user'
import { GET_TOKEN, GET_USERID, REMOVE_TOKEN, REMOVE_USERID } from '@/utils/tokenAndId'
import { defineStore } from 'pinia'

//创建用户相关的小仓库
const userStore = defineStore('User', {
  state: () => {
    return {
      userId: GET_USERID(),
      token: GET_TOKEN()
    }
  },
  actions: {
    //用户登录
    async userLogin(data) {
      const result = await reqUserLog(data)
      if (result) {
        //判断返回的请求是否成功
        if (result.code == 200) {
          //请求成功
          this.token = result.data.token
          this.userId = result.data.id
          localStorage.setItem('TOKEN', this.token)
          localStorage.setItem('USERID', this.userId)
          return 'ok'
        } else {
          //请求失败
          return Promise.reject(new Error(result.message))
        }
      } else {
        //请求失败
        return Promise.reject(new Error(result))
      }
    },

    //退出登录
    userLogout() {
      //清除本地数据
      this.token = ''
      this.userId = ''
      REMOVE_USERID()
      REMOVE_TOKEN()
    }
  },
  getters: {

  }
})

//对外暴露获取小仓库方法
export default userStore